<?php

namespace App\Http\Controllers\Admin;

use Cartalyst\Sentry\Facades\Laravel\Sentry;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class IndexController extends CommonController
{
    public function index(){
        $title="管理面板";
        return view('admin.index',compact('title'));
    }

    /**
     * @return 主面板
     */
    public function info(){
        return view('admin.info');
    }

    /**
     * 修改密码
     */
    public function pass(){
        if($input=Input::all()){
            $rules=[
                'password'=>'required|between:6,20|confirmed',
            ];
            $message=[
                'password.required'=>'新密码不能为空！',
                'password.between'=>'新密码范围必须在6-20位之间！',
                'password.confirmed'=>'新密码和确认密码不一致！',
            ];
            $validator=Validator::make($input,$rules,$message);
            if($validator->passes()){
                try
                {
                    $user = Sentry::getUser();
                    // 获得当前登陆的用户
                    if(Sentry::checkPassword($input['password_o'])){
                        $resetCode = $user->getResetPasswordCode();
                        // 检查重置密码的代码是否有效
                        if ($user->checkResetPasswordCode($resetCode))
                        {
                            // 重置用户密码
                            if ($user->attemptResetPassword($resetCode,$input['password']))
                            {
                                return back()->with('errors','修改密码成功!');
                            }else{
                                return back()->with('errors','修改密码失败,请重试!');
                            }
                        }else{
                            return back()->with('errors','修改密码失败,修改方式无效,请重试!');
                        }
                    }else{
                        return back()->with('errors','原密码错误!');
                    }
                }

                catch (\Cartalyst\Sentry\Users\UserExistsException $e){
                    return back()->with('errors','修改密码失败,无效Login,请重试!');
                }
                catch (\Cartalyst\Sentry\Users\UserNotFoundException $e){
                    return back()->with('errors','修改密码失败,用户获取失效,请重试!');
                }
            }else{
                return back()->withErrors($validator);
            }
            //return back()->with('errors','原密码错误!');
        }else{
            return view('admin.pass');
        }
    }
}
